package com.yxkj.syh.app.huarong.activities.creat.edit;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.lcw.library.imagepicker.ImagePicker;
import com.syh.app.basic.base.BaseActivity;
import com.syh.app.basic.bean.LiveDataEvent;
import com.syh.app.basic.config.BasicConstants;
import com.syh.app.basic.utils.AppUtil;
import com.syh.app.basic.utils.ComUtil;
import com.syh.app.basic.utils.PermissionUtil;
import com.syh.app.basic.utils.Tooast;
import com.syh.app.basic.utils.imagepickerhelper.ImagePickerHelper;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yxkj.syh.app.huarong.BR;
import com.yxkj.syh.app.huarong.R;
import com.yxkj.syh.app.huarong.activities.creat.address.edit.EditAddressActivity;
import com.yxkj.syh.app.huarong.activities.creat.bank.BankCardsActivity;
import com.yxkj.syh.app.huarong.bean.Goods;
import com.yxkj.syh.app.huarong.bean.OrderInfo;
import com.yxkj.syh.app.huarong.bean.Payment;
import com.yxkj.syh.app.huarong.bean.UserMainInfo;
import com.yxkj.syh.app.huarong.constants.ArouterPath;
import com.yxkj.syh.app.huarong.databinding.ActivityEditOrderBinding;
import com.yxkj.syh.app.huarong.util.PhotoUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.List;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

@Route(path = ArouterPath.EDIT_ORDER_ACTIVITY)
public class EditOrderActivity extends BaseActivity<ActivityEditOrderBinding, EditOrderVM> {
    public static final int PERMISSION_IMAGE = 0xb12;
    @Autowired
    OrderInfo orderInfo;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_edit_order;
    }

    @Override
    protected int getViewModelId() {
        return BR.editOrderVM;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        if (orderInfo == null) finish();
        mVDBinding.titleView.setLeftOnClickListener(v -> {
            finish();
        });

        setGoods(orderInfo.getDetails());
        mViewModel.initOrderInfo(orderInfo);

        mVDBinding.llPayment.setOnClickListener(v -> {
            Intent intent = new Intent(EditOrderActivity.this, BankCardsActivity.class);
            intent.putExtra("isSelect", true);
            intent.putExtra("id", orderInfo.getSupplierId());
            startActivityForResult(intent, 0x3a);
        });
        mVDBinding.llFromAddress.setOnClickListener(v -> {
            Intent intent = new Intent(EditOrderActivity.this, EditAddressActivity.class);
            intent.putExtra("userMainInfo", mViewModel.getOrderInfo().getStartLocation());
            startActivityForResult(intent, 0x1a);
        });
        mVDBinding.llToAddress.setOnClickListener(v -> {
            Intent intent = new Intent(EditOrderActivity.this, EditAddressActivity.class);
            intent.putExtra("userMainInfo", mViewModel.getOrderInfo().getEndLocation());
            startActivityForResult(intent, 0x2a);
        });
        mVDBinding.ivCamera.setOnClickListener(v -> {
            AndPermission.with(EditOrderActivity.this).requestCode(PERMISSION_IMAGE)
                    .permission(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .callback(mPermissionListener).start();
        });
    }

    @Override
    protected void initObservers() {
        super.initObservers();
        mViewModel.mldCreated.observe(this, aBoolean -> {
            EventBus.getDefault().post(new LiveDataEvent(BasicConstants.EVENT_SELECT_ORDER_ALL));
            setResult(RESULT_OK);
            finish();
        });
    }

    private void setGoods(List<Goods> goods) {
        for (Goods temp : goods) {
            View view = LayoutInflater.from(this).inflate(R.layout.view_order_goods, null);
            TextView tvName = view.findViewById(R.id.tvName);
            TextView tvCount = view.findViewById(R.id.tvCount);
            tvName.setText(temp.getName());
            tvCount.setText(temp.getPackages() + "包，" + temp.getQuantity() + "吨");
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            mVDBinding.llPurInfo.addView(view, params);
            view.requestLayout();
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0x1a) {
                UserMainInfo from = (UserMainInfo) data.getSerializableExtra("userMainInfo");
                mViewModel.getOrderInfo().setStartLocation(from);
                mViewModel.setFromText(from);
            } else if (requestCode == 0x2a) {
                UserMainInfo to = (UserMainInfo) data.getSerializableExtra("userMainInfo");
                mViewModel.getOrderInfo().setEndLocation(to);
                mViewModel.setToText(to);
            } else if (requestCode == 0x3a) {
                Payment payment = (Payment) data.getSerializableExtra("data");
                mViewModel.getOrderInfo().setPayment(payment);
                mViewModel.setPaymentText(payment);
                mViewModel.editOrderPayment(payment.getId());
            } else if (requestCode == ImagePickerHelper.REQUEST_SELECT_IMAGES_CODE) {
                List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);
                Luban.with(this).load(imagePaths.get(0))
                        .setTargetDir(AppUtil.getLubanPath())
                        .ignoreBy(100)
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                                showLoading("Compress");
                            }

                            @Override
                            public void onSuccess(File file) {
                                hideLoading("Compress");
                                mViewModel.scanCarId(file.getPath());
                            }

                            @Override
                            public void onError(Throwable e) {
                                hideLoading("Compress");
                                Tooast.normalInfo("压缩图片错误");

                            }
                        }).launch();
            } else if (requestCode == PhotoUtil.GET_IMAGE_BY_CAMERA) {
                File imageFile;
                if (Build.VERSION.SDK_INT >= 19) {
                    imageFile = ComUtil.getUriFromKitKat(this, PhotoUtil.imageUriFromCamera);
                } else {
                    imageFile = ComUtil.getUriBeforeKitKat(this, PhotoUtil.imageUriFromCamera);
                }
                if (imageFile.length() > 300 * 1024) {
                    Luban.with(this).load(imageFile)
                            .setTargetDir(AppUtil.getLubanPath())
                            .ignoreBy(100)
                            .setCompressListener(new OnCompressListener() {
                                @Override
                                public void onStart() {
                                    showLoading("Compress");
                                }

                                @Override
                                public void onSuccess(File file) {
                                    hideLoading("Compress");
                                    mViewModel.scanCarId(file.getPath());
                                }

                                @Override
                                public void onError(Throwable e) {
                                    hideLoading("Compress");
                                    Tooast.normalInfo("压缩图片错误");

                                }
                            }).launch();
                } else {
                    mViewModel.scanCarId(imageFile.getPath());
                }
            }
        }
    }


    private void startImageLib() {
        ImagePickerHelper.startImagePicker(this);
    }

    private PermissionListener mPermissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == PERMISSION_IMAGE) {
                new AlertDialog.Builder(EditOrderActivity.this).setItems(new String[]{"相册", "拍照"}, (dialog, which) -> {
                            dialog.cancel();
                            if (which == 0) {
                                startImageLib();
                            } else if (which == 1) {
                                PhotoUtil.openCameraImage(EditOrderActivity.this);
                            }
                        }
                ).create().show();
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == PERMISSION_IMAGE) {
                PermissionUtil.with(EditOrderActivity.this)
                        .addPermission(Manifest.permission.CAMERA)
                        .addPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
                        .addPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .initPermission();
            }
        }
    };
}
